package com.voice.call.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.voice.call.common.Const;
import com.voice.call.utils.AESEncryptUtil;
import com.voice.call.utils.StringUtil;

import jodd.io.StreamUtil;



public class LocalHttpServletRequestWrapper extends
		HttpServletRequestWrapper {
	 private final byte[] body;
	
     
	    public LocalHttpServletRequestWrapper(HttpServletRequest request)   
	throws IOException {  
	        super(request); 
	        body = StreamUtil.readBytes(new InputStreamReader(request.getInputStream(), Const.UTF8));  
	    }  
	  
	    @Override  
	    public BufferedReader getReader() throws IOException {  
	        return new BufferedReader(new InputStreamReader(getInputStream(), Const.UTF8));  
	    }  
	  
	    @Override  
	    public ServletInputStream getInputStream() throws IOException {
	    	
	       /*** 加密时启用 ****/
	       //修改request body内容(解密处理)
	       String content=AESEncryptUtil.decrypt(new String(body), AESEncryptUtil.APP_KEY);
	       if (StringUtil.isEmpty(content)) {
	    	   content = "";
		   }
	       byte[] byteArray = content.getBytes();
	       
	       /***
	       if (byteArray == null || byteArray.length ==0) { //解密失败
	    	   byteArray = body;
		   }***/
	       
	       final ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);  
	      
	    	
	       //final ByteArrayInputStream bais = new ByteArrayInputStream(body); //加密时禁用
	        return new ServletInputStream() {  
	  
	            @Override  
	            public int read() throws IOException {  
	                return bais.read();  
	            }

				@Override
				public boolean isFinished() {
					return false;
				}

				@Override
				public boolean isReady() {
					return false;
				}

				@Override
				public void setReadListener(ReadListener readListener) {
					
				}

	        };  
	    }  
}
